#include "affinity_id_generator.h"

#include <iostream>

#ifdef _BLACKROW
extern int black_topo;
#endif

namespace AceMesh_runtime {
affinity_id_generator::affinity_id_generator(int thread_nums):id(0), thread_num(thread_nums)
{
}

affinity_id_generator::affinity_id_generator():id(0)
{
}
affinity_id_generator::~affinity_id_generator()
{
}

int affinity_id_generator::get_affinity_id()
{
    int res = id;
    //printf("%d,",thread_num);
#ifdef _MAP_COLM
    res = PE_NCOL*(id%PE_NCOL) + id/PE_NCOL;
#elif _MAP_ROWS
    res= 2*((id/PE_NCOL)*PE_NCOL)+(id%PE_NCOL);
#elif _BLACKROW
    if ( (id/PE_NCOL) >= black_topo && black_topo <= PE_NROW)
        res+=PE_NCOL;
#endif

/*#ifdef _BLACKROW
    if ( (id/PE_NCOL) >= black_topo && black_topo <= PE_NROW)
        res+=PE_NCOL;
#endif

#ifdef _MAP_ROWS
    res= 2*((id/PE_NCOL)*PE_NCOL)+(id%PE_NCOL);
#endif

#ifdef _MAP_COLM    
    res = PE_NCOL*(id%PE_NCOL) + id/PE_NCOL;
#endif
*/
    ++id;

#if defined(_MAP_ROWS)
    if (thread_num>PE_NCOL)
        id =id % ((thread_num+PE_NCOL)/2);
    else
        id =id % thread_num;
#elif _BLACKROW
    id = id % (thread_num-PE_NCOL);
#else
    #ifdef SEG_BUFF
    #if defined(TARG_SW9) &&defined(CONCURRENT_CONSTRUCT_GRAPH)
    id =id % (thread_num-N_SLAVE_AGENT-1);
    #else
    id =id % (thread_num-N_SLAVE_AGENT);
    #endif
    #else
        #ifdef DISTRIBUTED_SCHEDULER
    #if defined(TARG_SW9) &&defined(CONCURRENT_CONSTRUCT_GRAPH)
    id =id % (thread_num-1);
    #else
    id =id % thread_num;
    #endif
    
        #else
    id = SL_SCHED;
        #endif
    #endif
#endif
//    printf("XXXXXXXXXXXaffinity_id: %d\n",res);
//    fflush(stdout);
    return res;
}

void affinity_id_generator::set_thread_num(int thread_nums)
{
    thread_num = thread_nums;
}

void affinity_id_generator::reset_affinity_id()
{
    id = 0;
}
}
